package nancal.mp.mvc.ops


import io.swagger.annotations.ApiParam
import nbcp.base.annotation.*
import nbcp.base.annotation.mvc.*
import nbcp.base.comm.*
import nbcp.base.extend.*
import nbcp.base.json.*
import nbcp.base.utils.SpringUtil
import nbcp.web.service.NacosServiceUtil
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.*
import javax.servlet.http.HttpServletResponse

@RequestMapping("/ops/nacos")
@RestController
class NacosController {
    companion object {
        private val logger = LoggerFactory.getLogger(this::class.java.declaringClass)
    }

    val nacosService = NacosServiceUtil;

    @RequestMapping("/config/get", method = arrayOf(RequestMethod.POST, RequestMethod.GET))
    fun getConfig(serverHost: String, ns: String, group: String, dataId: String): ApiResult<String> {
        return nacosService.getConfig(serverHost, ns, group, dataId)
    }

    @RequestMapping("/config/exists", method = arrayOf(RequestMethod.POST, RequestMethod.GET))
    fun existsConfig(serverHost: String, ns: String, group: String, dataId: String): ApiResult<Boolean> {
        return nacosService.existsConfig(serverHost, ns, group, dataId)
    }

    @RequestMapping("/config/list", method = arrayOf(RequestMethod.POST, RequestMethod.GET))
    fun queryConfigs(
        serverHost: String,
        @Require ns: String,
        dataId: String
    ): ListResult<NacosServiceUtil.NacosConfigItemData> {
        return nacosService.listConfigs(serverHost, ns, "", dataId)
    }

    /**
     * 设置nacos 配置方法
     */
    @PostMapping("/config/set")
    fun setConfig(
        serverHost: String,
        ns: String,
        group: String,
        dataId: String,
        @RequestBody content: String
    ): JsonResult {
        return nacosService.setConfig(
            serverHost,
            ns,
            group,
            dataId,
            "",
            content
        )
    }

    /**
     * 合并配置文件
     */
    @PostMapping("/config/join")
    fun join(
        serverHost: String,
        @Require namespace: String
    ) {
        var list = nacosService.listConfigs(serverHost, namespace, "", "")
        SpringUtil.context.environment.activeProfiles
            .sortedBy { it.length }
            .forEach { profile ->

                list.data.filter { it.dataId.endsWith("-${profile}.yml") }
                    .toList()
                    .forEach { config ->
                        var ori_data_id = config.dataId.Slice(0, 0 - "-${profile}.yml".length) + ".yml"

                        list.data.firstOrNull { it.dataId == ori_data_id }
                            .apply {
                                if (this == null) {
                                    nacosService.setConfig(serverHost, namespace, "", ori_data_id, "", config.content);
                                } else {
                                    var map_1 = this.content.FromYamlText<JsonMap>()
                                    var map_2 = config.content.FromYamlText<JsonMap>()


                                    nacosService.setConfig(
                                        serverHost,
                                        namespace,
                                        "",
                                        ori_data_id,
                                        "",
                                        map_1.deepJoin(map_2).ToYaml()
                                    );
                                }

                                nacosService.deleteConfig(
                                    serverHost,
                                    namespace,
                                    "",
                                    config.dataId
                                )
                            }
                    }
            }

    }

    /**
     * 设置nacos中的条目值。
     */
    @PostMapping("/config/set-all")
    fun set(
        serverHost: String,
        @Require namespace: String,
        name: String,
        @Require key: String,
        @Require value: String,
        option: String,
    ) {
        nacosService.listConfigs(serverHost, namespace, "", name)
            .data
            .forEach { config ->
                if (config.dataId.endsWith(".yml") == false) {
                    return@forEach
                }


                var list = try {
                    config.content.FromListYarmTextWithSplit(JsonMap::class.java)
                } catch (e: Exception) {
                    logger.error("Yaml转换出错: ${namespace}.${config.dataId}")
                    throw e;
                }

                if ((option basicSame "all") == false) {
                    if (list.any { it.getValueByWbsPath(key) != null } == false) {
                        return@forEach
                    }
                }


                var configPart = list.last();
                configPart.setValueByWbsPath(key, value = value);


                nacosService.setConfig(
                    serverHost,
                    namespace,
                    "",
                    config.dataId,
                    "",
                    list.map { it.ToYaml() }.joinToString("\n---\n")
                )
            }

    }


    @PostMapping("/set-gateway")
    fun set_gateway(
        serverHost: String,
        @ApiParam("nacos名称空间") ns: String,
        @ApiParam("微服务名称") app_name: String,
        @ApiParam("操作员") author: String,
        @ApiParam("data_id名称") data_id: String,
        response: HttpServletResponse
    ): JsonResult {
        val ret = nacosService.setGateway(
            serverHost,
            ns,
            app_name,
            author,
            data_id
        )
        if (ret.msg.HasValue) {
            response.status = 500;
        }

        return ret;
    }
}